<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="60%" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="mr-3">
      <template #options>
        <optionsInput ref="optionInputRef" :questionId="record?.id" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, reactive } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { FormSchema } from '@/components/Table';
  import { save, update, QuestionRequest } from '@/api/exam/question';
  import optionsInput from './optionsInput.vue';
  import { list as categoryList } from '@/api/exam/questionCategory';

  // 父组件回调方法
  const emit = defineEmits(['success', 'register']);

  // 是否是更新操作
  const isUpdate = ref(true);

  // 绑定子组件 expose 数据，获取子组件数据
  const optionInputRef = ref(null);

  // 表单字段列表
  const formSchema: FormSchema[] = [
    {
      field: 'title',
      label: '标题',
      required: true,
      component: 'Input',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'category',
      component: 'ApiSelect',
      label: '分类名称',
      required: true,
      colProps: {
        span: 24,
      },
      componentProps: {
        api: categoryList,
        params: {
          status: 1,
        },
        resultField: 'data', // 网络结果为: {code:0, message:{}, data:{list:[{},{}]}} 格式，如果没有list，直接写 data 即可
        labelField: 'category', // 选项展示名称: list 元素中每个对象的属性
        valueField: 'category', // 选项值字段: list 元素中每个对象的属性
        optionFilterProp: 'label', // 过滤字段
        immediate: true,
      },
    },
    {
      field: 'type',
      label: '类型',
      component: 'ApiRadioGroup',
      colProps: {
        span: 24,
      },
      defaultValue: 0,
      componentProps: {
        options: [
          { label: '单选题', value: 0 },
          { label: '多选题', value: 1 },
          { label: '简答题', value: 2 },
          { label: '评分', value: 3 },
        ],
      },
    },
    {
      field: 'status',
      label: '状态',
      component: 'RadioGroup',
      defaultValue: 1,
      colProps: {
        span: 24,
      },
      componentProps: {
        size: 'small',
        options: [
          { label: '启用', value: 1 },
          { label: '停用', value: 0 },
        ],
      },
    },
    {
      label: '选项列表',
      field: 'options',
      slot: 'options',
    },
  ];

  // 表单注册
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  let record: QuestionRequest = reactive({});
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    // 重置字段
    resetFields();
    isUpdate.value = !!data?.isUpdate;
    // 记录传过来的数据
    record = unref(data.record);

    // 更新窗口, 则设置表单字段
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
      optionInputRef.value.initOptions(record.id);
    } else {
      optionInputRef.value.clearOptions();
    }
  });

  // 表单标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增题目' : '编辑题目'));

  async function handleSubmit() {
    try {
      // 校验表单参数
      const values: QuestionRequest = await validate();

      // 开启loading 动画
      setDrawerProps({ confirmLoading: true });

      values.options = optionInputRef?.value.data;

      if (isUpdate.value) {
        await update(record.id, values);
      } else {
        await save(values);
      }

      // 关闭抽屉
      closeDrawer();
      // 通知父组件，更新成功
      emit('success');
    } finally {
      // 关闭 loading 动画
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
